package com.example.springbootstartermqttprovider.controller.task;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootstartermqttprovider.config.MqttProviderConfig;
import com.example.springbootstartermqttprovider.controller.DY47REQ;
import com.example.springbootstartermqttprovider.controller.DY47Response;
import com.example.springbootstartermqttprovider.myservice.domain.TBill;
import com.example.springbootstartermqttprovider.myservice.service.TBillService;
import com.example.springbootstartermqttprovider.oss.OSSUtils;
import com.example.springbootstartermqttprovider.yinhang.FileDownloadDemo;
import com.example.springbootstartermqttprovider.yinhang.UniqueIdGenerator;
import com.example.springbootstartermqttprovider.yinhang.WJ12Req;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 定义任务
 */
public class DongAoJob extends QuartzJobBean {

    private static final Log logger = LogFactory.getLog(DongAoJob.class);


    @Autowired
    private MqttProviderConfig providerClient;

    @Autowired
    private TBillService tBillService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        //查询需要同步的数据信息
        LambdaQueryWrapper<TBill> yu=new LambdaQueryWrapper<>();
        yu.eq(TBill::getTransferStatus,"2");
        yu.isNull(TBill::getPayFileUrl);
        List<TBill> list = tBillService.list(yu);
        for (TBill tBill : list) {
            try {
                uploadPay(tBill.getSettlementNo());
            } catch (Exception e) {
                logger.info("调整失败");
            }
        }
        logger.info(JSONUtil.toJsonStr(list));
//        try {
//            uploadPay("PbZ2FKdDQZ5X6Jek");
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }

    }



    public String uploadPay(String packNo) throws Exception {
        DY47REQ dy47 =new DY47REQ();
        dy47.setSummary(packNo);
        try
        {
            //查询数据表
            LambdaQueryWrapper<TBill> yu=new LambdaQueryWrapper<>();
            yu.eq(TBill::getSettlementNo,dy47.getSummary());
            List<TBill> list = tBillService.list(yu);
            String payTime = list.get(0).getPayTime().substring(0,10).replace("-", "");
            System.out.println(payTime);
            String beginTime=payTime;
            String endTime=payTime;

            dy47.setAcctNo("77250078801000001798");
            dy47.setBeginDate(beginTime);
            dy47.setEndDate(endTime);

            //组装A666数据信息
            String body1 = new FileDownloadDemo().BodyBeanToXml(dy47, "gb18030");
            String head1 = new FileDownloadDemo().getHeadXmlByTranceId("DY47", "2027726208");
            String sendJson1 = new FileDownloadDemo().getSendJson(head1, body1);
            String result1 = new FileDownloadDemo().sendByHttp(sendJson1);
            //step3: 将返回报文中的signature密文进行验签，获取交易返回的body明文
            Map returnBody1 = new FileDownloadDemo().getReturnBody(true, result1);
            String plain1 = returnBody1.get("plain").toString();
            DY47Response transfermoney1 = new FileDownloadDemo().XmlToBean(plain1, DY47Response.class);
            System.out.println(transfermoney1.getLoopResult().get(0));
            Object yuz =transfermoney1.getLoopResult().get(0);
            JSONObject ioo=new JSONObject(yuz);
            Object acceptNo = ioo.get("acceptNo");
            String no =String.valueOf(acceptNo);

            WJ12Req wj12Req=new WJ12Req();
            wj12Req.setAcctNo("77250078801000001798");
            wj12Req.setFileDownloadPar(no);
            wj12Req.setFileDownloadFlag(1);
//        wj12Req.setFileDownloadPar("1");
            //请求参数
            System.out.println("请求参数  =========="+ JSONUtil.toJsonStr(wj12Req));
            String body =new FileDownloadDemo().BodyBeanToXml(wj12Req,"gb18030");
            String head = new FileDownloadDemo().getHeadXmlByTranceId("WJ12", "2027726208");
            String sendJson =new FileDownloadDemo().getSendJson(head,body);
            //step2: �õ����ĺ�ƴ�ӱ��ģ����ͽ���
//        String send = "XXXXXX<?xml version=\"1.0\" encoding=\"gb2312\"?><packet><head>.......</head><body><signature>"+sign+"</signature></body></packet>";//ƴ�ӱ���
            String ty="F"+ UniqueIdGenerator.generateUniqueId()+".pdf";
            String result = FileDownloadDemo.sendFileByDownload(sendJson,ty);
            System.out.println("returnMsg  rcv from host is : " + new String(result));
            // 转换为字节数组
            File file = new File(System.getProperty("java.io.tmpdir") + "/" +ty);
            String fileName = ty;
            OSSUtils.getRandomFileNameNew(file,fileName);
            TBill uup=new TBill();
            uup.setId(list.get(0).getId());
            uup.setPayFileUrl("https://jqtms.oss-cn-beijing.aliyuncs.com/upload"+"/"+fileName);
            tBillService.updateById(uup);
            return "200";
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "500";
        }
    }

}